/**
 * Code modified from Firefox add-on Ambient News by
 * Contributor(s):
 *  Atul Varma <avarma@mozilla.com>
 *  Ben Basson <ben@basson.at>
 */
 
var DoubanNews = {

	url: function url(spec) {
		if (typeof(spec) != "string") 
			return spec;
		var classObj = Components.classes["@mozilla.org/network/io-service;1"];
    	var ios = classObj.getService(Components.interfaces.nsIIOService);
	    return ios.newURI(spec, null, null);
	},

	getFeed: function DoubanNews_getFeed(url, callback) {
    	function onXml(text) {
      		var feed = null;
      		if (text) {
        		var resultListener = {
          			handleResult: function resultListener_handleResult(aResult) {
            			var nsIFeed = aResult.doc;
            			if (!nsIFeed)
              				return;
            			feed = {};
            			var Ci = Components.interfaces;
						nsIFeed.QueryInterface(Ci.nsIFeed);
						feed.link = nsIFeed.link;
						feed.title = nsIFeed.title;
						feed.entries = [];
						for (var i = 0; i < nsIFeed.items.length; i++) {
							var item = nsIFeed.items.queryElementAt(i, Ci.nsIFeedEntry);
							feed.entries.push(item);
						}
					}
				};
				var fp = DoubanNews.__getFeedProcessor();
				fp.listener = resultListener;
				fp.parseFromString(text, DoubanNews.url(url));
			}
			callback(feed);
		}
		
		DoubanNews.__getXml(url, onXml);
	},
	
	__getXml: function DoubanNews_getXml(url, callback) {
    	var feedUrl = DoubanNews.url(url);
    	var annSvc = DoubanNews.__getAnnSvc();

		var request = new XMLHttpRequest();
		request.mozBackgroundRequest = true;
		request.open("GET", url, true);

		var onRscFunc = function getXml_onReadyStateChange() {
			if (request.readyState == 4) {
				if (request.status == 200) {
					if (request.responseText) {
						annSvc.setPageAnnotation(feedUrl,
                                     "douban/feed-xml",
                                     request.responseText,
                                     0,
                                     annSvc.EXPIRE_DAYS);
						callback(request.responseText);
					} else
            			callback("");
				} else
					callback("");
			}
		};
		
		try {
			request.onreadystatechange = onRscFunc;
			request.send(null);
		} catch (e) {
		}
	},
  
  	__getFeedProcessor: function DoubanNews_getFeedProcessor() {
		var Cc = Components.classes;
		var Ci = Components.interfaces;
		var fp = Cc["@mozilla.org/feed-processor;1"]
             	.createInstance(Ci.nsIFeedProcessor);
		return fp;
	},
	
  	__getAnnSvc: function DoubanNews_getAnnSvc() {
		var Cc = Components.classes;
		var annSvc = Cc["@mozilla.org/browser/annotation-service;1"]
                 .getService(Components.interfaces.nsIAnnotationService);
		return annSvc;
	},
	
  	onLinkAdded: function DoubanNews_onLinkAdded(aEvent) {
		if (aEvent.target.rel == "alternate" &&
				aEvent.target.href.indexOf("http://www.douban.com/") != -1 &&
				(aEvent.target.type == "application/rss+xml" ||
				aEvent.target.type == "application/atom+xml")) {
			var annSvc = DoubanNews.__getAnnSvc();
			var page = DoubanNews.url(aEvent.target.baseURI);
			var feed = DoubanNews.url(aEvent.target.href);
			annSvc.setPageAnnotation(page, "douban/feed",
	                   feed.spec, 0, annSvc.EXPIRE_WEEKS);
		}
	},
	
	initBrowser: function DoubanNews_initBrowser() {
    	// Listen for the addition of new <link> elements on pages.
		window.addEventListener("DOMLinkAdded", DoubanNews.onLinkAdded, false);
	}
};